package top.cardone.context.util;

import com.google.common.collect.Maps;
import com.google.gson.Gson;
import lombok.Setter;
import top.cardone.context.ApplicationContextHolder;
import top.cardone.core.CodeException;

import java.util.Map;

/**
 * @author yao hai tao
 * @date 16-2-2.
 */
public class CodeExceptionUtils {
    @Setter
    protected static String readOneErrorInfoContentFuncBeanId = "readOneErrorInfoContentFunc";

    private CodeExceptionUtils() {
    }

    public static Map<String, String> newMap(String url, String errorCode, String... errors) {
        Map<String, String> errorInfo = Maps.newHashMap();

        errorInfo.put("url", url);

        errorInfo.put("errorCode", errorCode);

        String error = org.apache.commons.lang3.StringUtils.join(errors);

        errorInfo.put("error", MessageUtils.getMessage(url, errorCode, errors, error, readOneErrorInfoContentFuncBeanId));

        return errorInfo;
    }

    public static Map<String, String> newMap(String url, Exception ex) {
        Map<String, String> errorInfo = Maps.newHashMap();

        errorInfo.put("url", url);

        if (ex instanceof CodeException) {
            CodeException codeException = (CodeException) ex;

            errorInfo.put("errorCode", codeException.getErrorCode());

            errorInfo.put("error", MessageUtils.getMessage(url, codeException.getErrorCode(), codeException.getArgs(), codeException.getMessage(), readOneErrorInfoContentFuncBeanId));
        } else {
            errorInfo.put("errorCode", "system error");
            errorInfo.put("error", ex.getMessage());
        }

        return errorInfo;
    }

    public static String newString(String url, String errorCode, String... errors) {
        Map<String, String> errorInfo = newMap(url, errorCode, errors);

        return ApplicationContextHolder.getBean(Gson.class).toJson(errorInfo);
    }

    public static String newString(String url, Exception ex) {
        Map<String, String> errorInfo = newMap(url, ex);

        return ApplicationContextHolder.getBean(Gson.class).toJson(errorInfo);
    }
}
